<?php

namespace App\Console\Commands;


use App\Listeners\Listener;
use App\Model\Business\Schedule;
use App\Model\Eeoapi\Eeosync;

use App\Model\Marketing\Device;
use App\Model\Marketing\Lead;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;


class DeviceCheck extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:DeviceCheck';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'EEO customer device check';

    /**
     * Create a new command instance.
     *
     * @return void
     */


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->deviceCheck();
        echo "Sync device info Succeed";
    }

    /**
     * 查询所有未同步且已经结束的课节
     * @param
     */
    protected function deviceCheck()
    {
        $clients = Lead::ALL();
        foreach ($clients as $client){
            $this->syncEeo($client);
        }
    }


    /**
     * 拉取EEO设备检测信息
     * @param $courseId 课程id
     * @param $classId 课节id
     * @param $teacher 老师账号
     * @param $scheduleid
     */
    protected function syncEeo($client)
    {

        try{
            $listener = new Listener();
            if($client->ClassInNo){
                $listener->setUri('getUserDeviceCheckInfo');
                $data = $listener->dataMaker();
                $data["telephone"] = $client->ClassInNo;
                $listener->setRequest($data);
                $result = $listener->callEeoApi();
                if($result['error_info']['errno'] == 1) {
                    $this->saveData($result['data'],$client->id);
                }
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 存储同步数据到数据库
     * @param $schedule
     * @param $type 学生为1 老师为2
     * @param $userid ClassInNo
     * @param $firstEnterTime 第一次进入教室时间
     * @param $lastExitTime 最后一次离开教室时间
     * @param $studyTime 有效学习时间
     */
    public function saveData($data,$clentid)
    {
        try{
            $device = Device::where('clientid',$clentid)->first();
            if(!$device){
                $device = New Device();
            }
            $device->clientid = $clentid;
            $device->deviceinfo = json_encode($data,JSON_UNESCAPED_UNICODE);
            $device->save();
        }catch (\Exception $e){
            throw $e;
        }
    }

}
